// pages/explore/index.js
// var {$http,$get} = require('../../utils/http')
Page({

    /**
     * 页面的初始数据
     */
    data: {
      tabArr:[
        // {icon:'renwen',catename:'正念冥想'},
        // {icon:'yejing',catename:'睡眠助手'},
        // {icon:'yinle',catename:'舒缓声音',children:[{}]}
      ],
      tabIdx:0,
      artlist:[],
      tabLeft:0,
      pageName:'探索'
    },
    async onLoad(options) {
        //加载分类
        let res = await getApp().fly.get('/classes/LearnCate')
        let {results} = res.data
        let cateLv1 = results.filter(item=>item.father[0]=='100')
        cateLv1.forEach(item=>{
          let child = results.filter(itm=>itm.father[0]==item.objectId)
          item.children = [{catename:'全部'},...child]
        })
        this.setData({
          tabArr:cateLv1
        })
        //加载数据列表
        let query = `where={"catelv1":"${cateLv1[0].objectId}"}`
        getApp().fly.get(`/classes/LearnArticle?${query}`).then(res=>{
            this.setData({
                artlist:res.data.results
            })
        })
    },
    handleTitle(ev){ //测试子父通信
      console.log(ev);
      this.setData({
        pageName:ev.detail
      })
    },
    handleTab(ev){
      let {idx,id} = ev.currentTarget.dataset
      this.tabScoll(ev,idx) //菜单切换交互
      this.fetchData(id) //根据不同主分类id，加载不同数据
    },
    tabScoll(ev,idx){
      let {offsetLeft} = ev.currentTarget //当前被点击按钮，距离左侧的偏移量
      let {tabIdx,tabLeft} = this.data
      if(idx>tabIdx){
          tabLeft = offsetLeft + 100
      }
      if(idx<tabIdx){
        tabLeft = offsetLeft - 100
      }
      console.log(idx,tabIdx,tabLeft);
      this.setData({
          tabIdx:idx,
          tabLeft
      })
    },
    fetchData(catelv1){  //用以请求数据的函数
      let query = `where={"catelv1":"${catelv1}"}`
        getApp().fly.get(`/classes/LearnArticle?${query}`).then(res=>{
            this.setData({
                artlist:res.data.results
            })
        })
    },
    handleDetail(ev){ //打开详情页
        let {idx} = ev.currentTarget.dataset
        wx.navigateTo({
          url: '/pages/course-detail/index?idx='+idx,
        })
    },
})